<template>
  <van-popup
    v-model="popupSelect"
    round
    position="bottom"
    :closeable="!(selectData && selectData.length)"
    @close="close"
  >
    <template v-if="selectData && selectData.length">
      <van-picker
        show-toolbar
        :columns="selectData"
        :value-key="valueKey"
        :default-index="defaultIndex"
        @cancel="close"
        @confirm="onConfirm"
      />
    </template>
    <template v-else>
      <van-empty description="暂无数据" />
    </template>
  </van-popup>
</template>
<script>
export default {
  props: {
    selectData: {
      type: Array,
      required: false,
      default: function() {
        return [];
      }
    },
    /* 默认选中项 */
    defaultCode: {
      type: String,
      required: false,
      default: ''
    },
    valueKey: {
      type: String,
      required: false,
      default: 'value'
    }
  },
  data() {
    return {
      popupSelect: false,
      defaultIndex: 0,
      columns: []
    };
  },
  watch: {
    defaultCode() {
      this.selectData.forEach((item, index) => {
        if (item.code === this.defaultCode || item[this.valueKey] === this.defaultCode) {
          this.defaultIndex = index;
        }
      });
    }
  },
  methods: {
    open() {
      this.popupSelect = true;
    },
    onConfirm(value, index) {
      this.$emit('onConfirm', this.selectData[index]);
      this.popupSelect = false;
    },
    close() {
      this.popupSelect = false;
    }
  }
};
</script>
